import os
import sys

from PyQt6.QtCore import Qt, QTimer, QPoint
from PyQt6.QtGui import QFont, QIcon
from PyQt6.QtWidgets import (QApplication, QWidget, QDialog, QVBoxLayout, QHBoxLayout,
                             QLabel, QPushButton, QComboBox, QSystemTrayIcon,
                             QMenu, QStyle, QMessageBox)


class SettingsDialog(QDialog):
    """番茄钟设置界面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("不打扰番茄钟-设置-作者wx:easy-118899")
        self.icon_img = QIcon(self.get_resource_path('images/favicon.ico'))
        self.setWindowIcon(self.icon_img)
        self.setFixedSize(300, 150)

        # 设置中文字体
        font = QFont()
        font.setFamily("SimHei")
        self.setFont(font)

        # 默认时间设置
        self.selected_time = 25  # 默认25分钟

        # 创建布局
        layout = QVBoxLayout()

        # 时间选择
        time_layout = QHBoxLayout()
        time_label = QLabel("番茄钟时长 (分钟):")
        self.time_combo = QComboBox()
        self.time_combo.addItems(["5", "15", "20", "25", "30", "45", "60"])
        self.time_combo.setCurrentText(str(self.selected_time))

        time_layout.addWidget(time_label)
        time_layout.addWidget(self.time_combo)

        # 按钮布局
        btn_layout = QHBoxLayout()
        self.ok_btn = QPushButton("确定")
        self.cancel_btn = QPushButton("取消")

        self.ok_btn.clicked.connect(self.accept)
        self.cancel_btn.clicked.connect(self.reject)

        btn_layout.addWidget(self.ok_btn)
        btn_layout.addWidget(self.cancel_btn)

        # 添加到主布局
        layout.addLayout(time_layout)
        layout.addLayout(btn_layout)

        self.setLayout(layout)

    def get_resource_path(self, relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def accept(self):
        """确认选择"""
        self.selected_time = int(self.time_combo.currentText())
        super().accept()

    def get_selected_time(self):
        """获取选择的时间（秒）"""
        return self.selected_time * 60


class TomatoClockWindow(QWidget):
    """番茄钟显示窗口"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

        # 计时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_timer)
        self.remaining_time = 0  # 剩余时间（秒）
        self.total_time = 0  # 总时间（秒）

        # 窗口位置 - 左上角
        self.move(QPoint(10, 10))

    def initUI(self):
        """初始化界面"""
        # 设置窗口属性
        self.setWindowTitle("不打扰番茄钟")
        self.setFixedSize(120, 50)  # 稍微增大窗口宽度以完整显示时间

        # 设置窗口透明和置顶
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint |  # 无边框
            Qt.WindowType.WindowStaysOnTopHint |  # 置顶
            Qt.WindowType.SubWindow |  # 子窗口，避免在Alt+Tab中显示
            Qt.WindowType.Tool  # 添加 Tool 标志，帮助系统识别为工具窗口
        )

        # 设置窗口透明背景
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)  # 背景透明

        # 创建布局
        layout = QVBoxLayout()

        # 时间显示
        self.time_label = QLabel("25:00")
        self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        time_font = QFont("SimHei", 24, QFont.Weight.Bold)
        self.time_label.setFont(time_font)
        self.time_label.setStyleSheet("color: green;")

        # 添加到布局
        layout.addWidget(self.time_label)

        self.setLayout(layout)

    def start_timer(self, seconds):
        """开始计时器"""
        self.total_time = seconds
        self.remaining_time = seconds
        self.update_time_display()
        self.timer.start(1000)  # 每秒更新一次
        self.show()

    def stop_timer(self):
        """停止计时器"""
        self.timer.stop()
        self.hide()

    def update_timer(self):
        """更新计时器"""
        self.remaining_time -= 1
        if self.remaining_time <= 0:
            self.stop_timer()
            # 计时结束，可以添加提示音或通知
        self.update_time_display()

    def update_time_display(self):
        """更新时间显示"""
        minutes = self.remaining_time // 60
        seconds = self.remaining_time % 60
        self.time_label.setText(f"{minutes:02d}:{seconds:02d}")

        # 根据剩余时间改变颜色 - 使用渐变色
        progress = self.remaining_time / self.total_time if self.total_time > 0 else 0

        if progress > 0.5:  # 大于50%时间，显示绿色
            # 绿色渐变到黄色
            ratio = (progress - 0.5) / 0.5  # 从0到1
            red = int(255 * (1 - ratio))  # 绿色到黄色，红色分量从0增加到255
            green = 255
            blue = 0
        elif progress > 0.2:  # 20%到50%，显示黄色
            # 黄色渐变到橙色
            ratio = (progress - 0.2) / 0.3  # 从0到1
            red = 255
            green = int(165 + 90 * ratio)  # 从165(橙色)增加到255(黄色)
            blue = 0
        else:  # 小于等于20%，显示红色
            # 红色渐变（深红到亮红）
            ratio = progress / 0.2 if progress > 0 else 0  # 从0到1
            red = 255
            green = int(100 * ratio)  # 从0增加到100
            blue = int(100 * ratio)  # 从0增加到100

        alpha = 200  # 透明度
        color = f"rgba({red}, {green}, {blue}, {alpha})"
        self.time_label.setStyleSheet(f"color: {color};")


class SystemTrayIcon(QSystemTrayIcon):
    """系统托盘图标"""

    def __init__(self, icon, parent=None):
        super().__init__(icon, parent)

        # 创建番茄钟窗口
        self.tomato_window = TomatoClockWindow()

        # 创建菜单
        self.menu = QMenu(parent)

        # 设置动作
        self.settings_action = self.menu.addAction("设置番茄钟")
        self.settings_action.triggered.connect(self.show_settings)

        # 开始/暂停动作
        self.start_action = self.menu.addAction("开始")
        self.start_action.triggered.connect(self.start_timer)

        self.pause_action = self.menu.addAction("暂停")
        self.pause_action.triggered.connect(self.pause_timer)
        self.pause_action.setEnabled(False)

        # 退出动作
        self.quit_action = self.menu.addAction("退出")
        self.quit_action.triggered.connect(self.quit_application)

        # 设置菜单
        self.setContextMenu(self.menu)

        # 双击托盘图标显示设置
        self.activated.connect(self.on_tray_activated)

        # 初始设置时间（25分钟）
        self.timer_duration = 25 * 60

        # 设置托盘图标为自定义图标
        self.icon_img = QIcon(self.get_resource_path('images/favicon.ico'))
        self.setIcon(self.icon_img)

    def get_resource_path(self, relative_path):
        """获取资源文件的绝对路径"""
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def on_tray_activated(self, reason):
        """托盘图标激活事件"""
        if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.show_settings()

    def show_settings(self):
        """显示设置对话框"""
        dialog = SettingsDialog()
        if dialog.exec():
            self.timer_duration = dialog.get_selected_time()
            # 如果计时器正在运行，更新时间
            if self.tomato_window.timer.isActive():
                self.tomato_window.start_timer(self.timer_duration)

    def start_timer(self):
        """开始计时器"""
        self.tomato_window.start_timer(self.timer_duration)
        self.start_action.setEnabled(False)
        self.pause_action.setEnabled(True)

    def pause_timer(self):
        """暂停计时器"""
        self.tomato_window.stop_timer()
        self.start_action.setEnabled(True)
        self.pause_action.setEnabled(False)

    def quit_application(self):
        """退出应用程序"""
        self.tomato_window.stop_timer()
        QApplication.quit()


def main():
    """主函数"""
    # 确保应用程序可以在Windows系统托盘运行
    app = QApplication(sys.argv)

    # 检查系统是否支持系统托盘
    if not QSystemTrayIcon.isSystemTrayAvailable():
        QMessageBox.critical(None, "错误", "系统不支持系统托盘功能!")
        sys.exit(1)

    # 确保应用程序在所有窗口关闭后仍能运行
    app.setQuitOnLastWindowClosed(False)

    # 创建系统托盘图标
    tray_icon = SystemTrayIcon(QIcon())  # 传入空 QIcon，稍后会设置为自定义图标
    tray_icon.show()

    # 显示提示信息
    tray_icon.showMessage(
        "不打扰番茄钟",
        "应用已最小化到系统托盘",
        QSystemTrayIcon.MessageIcon.Information,
        2000
    )

    # 运行应用程序
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
